package com.achievo.know.web.auth;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.achievo.know.application.CodeDictCacheHandler;
import com.achievo.know.application.UserApplication;
import com.achievo.know.domain.User;
import com.achievo.know.pojo.LoginStatus;
import com.achievo.know.web.myfile.MyfileAction;
import com.achievo.know.web.util.BaseActionSupport;
import com.redhat.redwork.coc.RedworkAction;

public class LoginAction extends BaseActionSupport implements RedworkAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4378826377695218283L;
	
	private static final Logger	logger  = LoggerFactory.getLogger(MyfileAction.class);
	
	private int code;//JSON操作结果
	
	private String msg;
	
	@Autowired
	private UserApplication userApplication;
	
	private String username;
	
	private String password;
	
	private String isJson;
	/**
	 * 显示登录页面
	 * @return
	 */
	public String home(){
		
		return "login";
	}
	
	/**
	 * 登录验证
	 * @return
	 */
	public String auth(){
		boolean json=false;
		if("true".equals(isJson)){
			json=true;
		}
		try{
			if(StringUtils.isEmpty(username)){
				setActionResult(0, "用户名不能为空");
				return json?JSON:"login";
			}
			if(StringUtils.isEmpty(password)){
				setActionResult(0, "密码不能为空");
				return json?JSON:"login";
			}
			User oldUser=(User) CodeDictCacheHandler.getObject(username);
			if(oldUser!=null){
				try {
					//HttpSession session=(HttpSession) CodeDictCacheHandler.getObject(username+"_session");
					HttpSession session=(HttpSession) ServletActionContext.getContext().getApplication().get(username+"_session");
					if(session!=null){
						Boolean isAdmin=session.getAttribute("isAdmin")!=null?(Boolean) session.getAttribute("isAdmin"):false;
						Boolean isSuperAdmin=session.getAttribute("isSuperAdmin")!=null?(Boolean) session.getAttribute("isSuperAdmin"):false;
						if(isAdmin || isSuperAdmin){
							
						}else{
							session.invalidate();
						}
					}
				} catch (Exception e) {
					System.out.println(e.getMessage());
					logger.error(e.getMessage());
				}
			}
			int result=userApplication.authenticate(username, password);
			boolean isSuperadmin=false;
			if(LoginStatus.SUCCESS==result){
				code=1;
				msg="验证成功";
				User loginUser=userApplication.get(username);
				
				ServletActionContext.getRequest().getSession().setAttribute("isAdmin", false);
				ServletActionContext.getRequest().getSession().setAttribute("isSuperAdmin", isSuperadmin);
				if(StringUtils.isNotEmpty(loginUser.getRolesStr())){
					if(loginUser.getRolesStr().contains("管理员")){
						ServletActionContext.getRequest().getSession().setAttribute("isAdmin", true);
					}
					if(loginUser.getRolesStr().contains("超级管理员")){
						ServletActionContext.getRequest().getSession().setAttribute("isSuperAdmin", true);
						isSuperadmin=true;
					}
				}
				ServletActionContext.getRequest().getSession().setAttribute("loginuser", username);
				CodeDictCacheHandler.putObject(username, loginUser);
				ServletActionContext.getContext().getApplication().put(username+"_session", ServletActionContext.getRequest().getSession());
				//CodeDictCacheHandler.putObject(username+"_session", ServletActionContext.getRequest().getSession());
				ServletActionContext.getRequest().getSession().setAttribute("islocal", loginUser.isLocal());
				ServletActionContext.getRequest().getSession().setAttribute("userRealName", loginUser.getRealName());
				//Map<String,String> auths=userApplication.findUserAuth(loginUser);
				//CodeDictCacheHandler.putObject(username+"_auths", auths);
				//List<Long> cateIds=userApplication.findUserCates(loginUser);
				//CodeDictCacheHandler.putObject(username+"_cateIds", cateIds);
				//List<Long> adminCateIds=userApplication.findAdminCates(loginUser);
				//CodeDictCacheHandler.putObject(username+"_adminCateIds", adminCateIds);
			}
			if(LoginStatus.USERNOTFOUND==result){
				setActionResult(0, "找不到用户或用户不唯一");
				return json?JSON:"login";
			}
			if(LoginStatus.USERDISABLED==result){
				setActionResult(0, "用户已失效");
				return json?JSON:"login";
			}
			if(LoginStatus.WRONGPWD==result){
				setActionResult(0, "密码出错");
				return json?JSON:"login";
			}
			if(LoginStatus.AUTHERROR==result){
				setActionResult(0, "验证失败");
				return json?JSON:"login";
			}
			if(!isSuperadmin){
				if(!hasAuth("LOGIN")){
					setActionResult(0, "你没有登录的权限");
					return json?JSON:"login";
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			setActionResult(0, "验证失败");
			return json?JSON:"login";
		}
		setActionResult(1, "验证成功");
		return json?JSON:"login-success";
	}
	
	public String logout(){
		try{
			ServletActionContext.getRequest().getSession().invalidate();
			code=1;
			msg="ok";
		}catch(Exception e){
			logger.error(e.getMessage());
			code=0;
			msg="error";
			//return JSON;
		}
		return "login";
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	public void setUserApplication(UserApplication userApplication) {
		this.userApplication = userApplication;
	}
	
	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public void setActionResult(int code,String msg){
		setCode(code);
		setMsg(msg);
	}

	public String getIsJson() {
		return isJson;
	}

	public void setIsJson(String isJson) {
		this.isJson = isJson;
	}
	
	
	

}
